/**
 * Copyright (c) 2025 myons Inc. All rights reserved.
 */
package cn.zmwh.portal.modules.miniapp.service;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.zmwh.common.core.constants.ServiceConstants;
import cn.zmwh.common.core.utils.RedisUtils;
import cn.zmwh.common.security.base.BaseUserDetails;
import cn.zmwh.common.security.base.LoginService;
import cn.zmwh.common.security.base.UserService;
import cn.zmwh.common.security.config.JwtTokenUtil;
import cn.zmwh.common.security.pojo.dto.LoginDTO;
import cn.zmwh.common.security.pojo.request.LoginRequest;
import cn.zmwh.common.security.pojo.vo.LoginVo;
import cn.zmwh.common.security.pojo.vo.WxDTO;
import cn.zmwh.manage.api.modules.umps.entity.UserWechat;
import cn.zmwh.manage.api.modules.umps.service.UserWechatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @describe: 微信登录 、
 * @author: dmzmwh 、
 * @time: 2025-03-11 16:41 、
 */
@Slf4j
@Service(value = "wx" + ServiceConstants.LOGIN)
public class WxServiceCode implements LoginService {

    @Autowired
    private UserService userService;
    @Autowired
    private UserWechatService userWechatService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private WxMaService wxMaService;
    @Autowired
    private RedisUtils redisUtils;

    @Override
    public LoginVo login(LoginRequest request) {
        LoginVo loginVo = new LoginVo();
        String code = request.getCode();
        try {
            UserWechat userWechat = null;
            if (StrUtil.isNotBlank(code)) {
                String appid = request.getAppid();
                if (!wxMaService.switchover(appid)) {
                    throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
                }
                WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
                String openId = session.getOpenid();
                String unionId = session.getUnionid();
                userWechat = userWechatService.getByOpenId(openId, unionId, 1);
                if (userWechat == null) {
                    WxDTO wxDTO = new WxDTO();
                    loginVo.setWxDTO(wxDTO);
                    loginVo.setSuccess(10);
                    return loginVo;
                }
            } else {
                WxDTO wxDTO = request.getWxDTO();
                if (wxDTO == null) {
                    loginVo.setMsg("openid为空");
                    return loginVo;
                }
                LoginDTO loginDTO = new LoginDTO();
                loginDTO.setUType(1);
                BeanUtil.copyProperties(request, loginDTO);
                loginDTO.setCreate(true);
                userWechat = userWechatService.saveAndUser(loginDTO);
            }
            Long id = userWechat.getId();
            BaseUserDetails userDetails = (BaseUserDetails) userService.loadUserById(id);
            String token = jwtTokenUtil.generateToken(userDetails, request.getTerminal());
            loginVo.setToken(token);
            loginVo.setSuccess(1);
        } catch (Exception e) {
            log.error("微信登录异常", e);
            loginVo.setToken(e.getMessage());
            loginVo.setSuccess(0);
        } finally {
            WxMaConfigHolder.remove();//清理ThreadLocal
        }
        return loginVo;
    }
}
